package com.zht.service.impl;

//import cn.ucox.web.framework.view.ApiResult;
import com.zht.entity.FileUrlEntity;
import com.zht.entity.FileVo;
import com.zht.entity.UserEntity;
import com.zht.mapper.SelectSpeedListMapper;
import com.zht.service.SendMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.Random;

@Service
public class SendMessageServiceImpl implements SendMessageService {

    @Autowired
    private SelectSpeedListMapper selectSpeedListMapper;

    // 上传路径
    private Path fileUploadPath = Paths.get(FileUrlEntity.getFilePath());

    private static int count = 0;

    @Override
    public String testSendMessage(String s) {
        if (s.equals("1003")){
            // 开始重试
            count++;
            if (count <= 3){
                return testSendMessage("1003");
            }
            if (count > 3){
                // 置空count
                count = 0;
                // 发送短信
                return "短信发送成功";
            }

        }
        if (s.equals("1004")){
            return "成功";
        }
        return "失败";
    }

    @Override
    public void addUser(UserEntity out) {
        selectSpeedListMapper.addUser(out);
    }

    /**
     * 存储文件
     *
     * @param inputStream      文件输入流
     * @param size             文件大小
     * @param contentType      文件类型
     * @param originalFilename 文件名称
     * @return
     */
    @Override
    public FileVo store(InputStream inputStream, long size, String contentType, String originalFilename) {
        //生成密钥
        String key = generateKey(originalFilename);
        //存储文件
        upload(inputStream,size,contentType,key);
        //返回文件信息
        String url = FileUrlEntity.getFilePath() + "/" + key;
        FileVo fileVo = new FileVo();
        fileVo.setCreateTime(new Date());
        fileVo.setFileKey(key);
        fileVo.setFileName(originalFilename);
        fileVo.setSize(size);
        fileVo.setUrl(url);
        //新增文件
        selectSpeedListMapper.addFile(fileVo);
        return fileVo;
    }

    /**
     * 获取文件
     *
     * @param fileKey 文件唯一标识
     * @return 结果
     */
    @Override
    public FileVo findFile(String fileKey) {
        return selectSpeedListMapper.findFile(fileKey);
    }

    /**
     * 存储文件
     * @param inputStream
     * @param size
     * @param contentType
     * @param key
     */
    private void upload(InputStream inputStream, long size, String contentType, String key) {
        try {
            Files.copy(inputStream,fileUploadPath.resolve(key), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("文件存储错误: " + key,e);
        }
    }

    /**
     * 生成密钥
     * @param originalFilename 文件名称
     * @return
     */
    private String generateKey(String originalFilename) {
        //获取文件后缀
        int i = originalFilename.lastIndexOf(".");
        String fileSuffix = originalFilename.substring(i);

        String key = null;
        FileVo fileVo = null;

        //生成key
        do {
            //生成唯一key
            key = getRandomString(20)  + fileSuffix;
           fileVo = selectSpeedListMapper.findFile(key);
        }while (fileVo != null);

        return key;
    }


    /**
     * 获取随机数
     * @param num
     * @return
     */
    private String getRandomString(int num) {
        //创建随机数对象
        Random random = new Random();
        //定义基础数据
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        //key拼接
        StringBuilder keyStr = new StringBuilder();
        for (int i = 0; i < num; i++) {
            //获取基本数据单位
            int number = random.nextInt(base.length());
            //添加
            keyStr.append(base.charAt(number));
        }
        return keyStr.toString();
    }
}
